package fengstyle.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

public class MyPreciseAlgotithm implements PreciseShardingAlgorithm<Date> {

    /**
     * 自定义标准分表策略
     * @param tableNames：对应库中所有分片表的集合
     * @param shardingValue：为分片属性，其中logicTableName为逻辑表，columnName为分片键（字段），
     *                     value为从sql中解析出的分片键的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<Date> shardingValue) {
        Date date = shardingValue.getValue();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        for(String tableName : tableNames){
            System.out.println(tableName);
            if(tableName.endsWith(String.valueOf(year))){
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }
}
